package com.fnzn.entranceGuard.controller;
import java.util.*;

import com.fnzn.entranceGuard.constant.GuardConstant;
import com.fnzn.entranceGuard.entity.GuardHubCode;
import com.fnzn.entranceGuard.rest.guard.UsrUtil;
import com.fnzn.entranceGuard.service.IGuardDeviceService;
import com.fnzn.entranceGuard.service.IGuardHubCodeService;
import com.fnzn.entranceGuard.service.IGuardIcInfoService;
import com.fnzn.entranceGuard.util.QRGenerate;
import com.fnzn.entranceGuard.util.ResponseUtil;
import com.fnzn.entranceGuard.util.SpringUtil;
import com.fnzn.entranceGuard.vo.DeviceTree;
import com.github.pig.common.util.IdGenerate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pig.common.constant.CommonConstant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.fnzn.entranceGuard.entity.GuardDevice;
import com.github.pig.common.web.BaseController;
import org.thymeleaf.util.ListUtils;

import static com.fnzn.entranceGuard.rest.usrCloud.ClinetCallbackAdapter.getClock;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sxf
 * @since 2018-06-25
 */
@RestController
@RequestMapping("/guardDevice")
@Slf4j
public class GuardDeviceController extends BaseController {
    @Autowired
    private IGuardDeviceService guardDeviceService;
    @Autowired
    private IGuardHubCodeService hubCodeService;
    @Autowired
    private IGuardIcInfoService guardIcInfoService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return GuardDevice
    */
    @GetMapping("/{id}")
    public R<GuardDevice> get(@PathVariable Integer id) {
        return new R<>(guardDeviceService.selectById(id));
    }

    /**
     * 树结构
     * 结构：
     * id: 1,
     event: '事件1',
     timeLine: 100,
     comment: '无',
     children: [
     {
     id: 2,
     event: '事件2',
     timeLine: 10,
     comment: '无'
     }]
     * @return 设备树  控制器列框
     */
    @RequestMapping("/listTree")
    public ResponseUtil listTree() {
        ResponseUtil r = new ResponseUtil();
        try {
            Map<String,Object> result = new HashMap<>();
            //设备树
            String username = getUserName();
            if(StringUtils.isNotBlank(username)){
                List<DeviceTree> tree = guardDeviceService.listTree(username);
                result.put("tree",tree);
                r.ok(result);
            }else{
                r.fail("401", "token已过期，请重新登陆。");
                return r;
            }

        }catch(Exception e){
            e.printStackTrace();
            log.error("查询设备树异常：",e);
            r.fail("500",e.getMessage());
        }
        return r;
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        return guardDeviceService.selectPage(new Query<>(params), new EntityWrapper<>());
    }

    /**
     * 添加
     * @param  guardDevice  实体
     * @return success/false
     */
    @PostMapping
    public R<Boolean> add(@RequestBody GuardDevice guardDevice) {
        EntityWrapper entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(guardDevice.getDeviceId())) {
            entityWrapper.eq("device_id",guardDevice.getDeviceId());
        }
        List<GuardDevice> list = guardDeviceService.selectList(entityWrapper);
        if (!ListUtils.isEmpty(list)) {
            R r = new R<>();
            r.setData(false);
            r.setMsg("设备号重复");
            return r;
        }
        guardDevice.setGuardId(IdGenerate.getUUID());
        Integer maxSort = guardDeviceService.getMaxSortByCommunityId(guardDevice.getCommunityId());
        guardDevice.setSort(maxSort + 1);
        return new R<>(guardDeviceService.insert(guardDevice));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Integer id) {
        GuardDevice guardDevice = new GuardDevice();
        guardDevice.setId(id);
        guardDevice.setUpdateTime(new Date());
        guardDevice.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(guardDeviceService.updateById(guardDevice));
    }

    /**
     * 编辑
     * @param  guardDevice  实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> edit(@RequestBody GuardDevice guardDevice) {
        EntityWrapper entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(guardDevice.getDeviceId())) {
            entityWrapper.eq("device_id",guardDevice.getDeviceId());
            List<GuardDevice> list = guardDeviceService.selectList(entityWrapper);
            if (!ListUtils.isEmpty(list)) {
                int flag = 0;
                for (GuardDevice device: list) {
                    if (!guardDevice.getId().equals(device.getId())) {
                        flag++;
                    }
                }
                if(flag != 0) {
                    R r = new R<>();
                    r.setData(false);
                    r.setMsg("设备号重复");
                    return r;
                }
            }
        }
        if(guardDevice.getType() != null && GuardDevice.TYPE_GUARD.equals(guardDevice.getType())) {
            guardDevice.setDeviceType("");
            guardDevice.setFloor(0);
        }
        guardDevice.setUpdateTime(new Date());
        if(guardDevice.getSort() == null) {
            Integer maxSort = guardDeviceService.getMaxSortByCommunityId(guardDevice.getCommunityId());
            //跳过13
            if(maxSort==12){
                maxSort=13;
            }
            guardDevice.setSort(maxSort + 1);
        }
        return new R<>(guardDeviceService.updateById(guardDevice));
    }

    /**
     * 云同步时钟和社区
     * @param deviceId
     *
     */
    @RequestMapping(value = "/syncByDeviceId", method = RequestMethod.GET)
    public ResponseUtil syncByDeviceId(@RequestParam("deviceId") String deviceId) {
        ResponseUtil r = new ResponseUtil();
        try {
            //时钟
            byte[] i = getClock();
            UsrUtil.publishForDevId(UsrUtil.PublishFormat(i, GuardConstant.TYPE_CLOCK), deviceId);
            Thread.sleep(10000);
            //社区
            IGuardDeviceService guardDeviceService = SpringUtil.getBean(IGuardDeviceService.class);
            Integer communityCode = guardDeviceService.getCommunityCodeByDeviceId(deviceId);
            GuardDevice device = guardDeviceService.getDeviceCodeByDeviceId(deviceId);
            UsrUtil.publishForDevId(UsrUtil.PublishFormat(UsrUtil.communityCodeFormat(communityCode,device),GuardConstant.TYPE_COM),deviceId);
            r.ok("同步成功");
        } catch (Exception e) {
            log.error("同步云：",e);
            e.printStackTrace();
            r.fail("500",e.getMessage());
        }
        return r;
    }
    /**
     * 初始化设备
     * @param deviceId
     *
     */
    @RequestMapping(value = "/deviceInit", method = RequestMethod.GET)
    public ResponseUtil deviceInit(@RequestParam("deviceId") String deviceId) {
        ResponseUtil r = new ResponseUtil();
        try {
            byte[] start = QRGenerate.parse16Str2HexByte("AA");
            byte[] data = {start[0],start[0]};
            UsrUtil.publishForDevId(UsrUtil.PublishFormat(data,GuardConstant.TYPE_INIT),deviceId);
            r.ok("初始化成功");
        } catch (Exception e) {
            log.error("初始化设备：",e);
            e.printStackTrace();
            r.fail("500",e.getMessage());
        }
        return r;
    }
}
